<?php
function ClearCid($where) { // 成功返回false
  $t = GetData($where, 'id,pid,cid');
  if ($t['error']) {
    $t['data'] = $where;
    $t['msg'] = '获取where数据时发生错误';
    return $t;
  }
  if (!$t) return ['error' => '当前where数据为空', 'data' => $where];
  foreach ($t as $v) {
    $t = GetData(['table' => $where['table'], 'id' => $v['pid']], 'cid', true);
    if ($t['error']) {
      $t['data'] = $where;
      $t['msg'] = '获取id=[' . $v['pid'] . ']的cid时发生错误';
      return $t;
    }
    $t = UpData([
      'table' => $where['table'],
      'cid' => ($v['cid'] | $t['cid']) ^ $t['cid'],
      'where' => ['id' => $v['id']]
    ]);
    if ($t['error']) {
      $t['data'] = $where;
      $t['msg'] = '修改id=[' . $v['id'] . ']的cid时发生错误';
      return $t;
    }
  }
  return false;
}
$up = [];
$up['unit'] = function ($cmd, $token) {
  if ($token['type'] == 管理员) {
    $tmp = ['table' => 'unit', 'where' => $cmd['where']];
    if ($cmd['name']) $tmp['name'] = $cmd['name'];
    if ($cmd['other']) $tmp['other'] = json_encode($cmd['other'], JSON_UNESCAPED_UNICODE);
  } else return noPrem;
  return UpData($tmp);
};
$up['itemType'] = function ($cmd, $token) {
  if ($token['type'] == 管理员) {
    $tmp = ['table' => 'itemtype', 'where' => $cmd['where']];
    if (isset($cmd['pid'])) $tmp['pid'] = (int) $cmd['pid'];
    if ($cmd['name']) $tmp['name'] = $cmd['name'];
    if ($cmd['other']) $tmp['other'] = $cmd['other'];
  } else return noPrem;
  return ['result' => UpData($tmp)];
};
$up['depository'] = function ($cmd, $token) {
  if ($token['type'] == 管理员) {
    $tmp = ['table' => 'depository', 'where' => $cmd['where']];
    if ($cmd['pid']) $tmp['pid'] = $cmd['pid'];
    if ($cmd['items']) $tmp['items'] = json_encode($cmd['items'], JSON_UNESCAPED_UNICODE);
    if ($cmd['name']) $tmp['name'] = $cmd['name'];
    if ($cmd['other']) $tmp['other'] = json_encode($cmd['other'], JSON_UNESCAPED_UNICODE);
  } else return noPrem;

  return UpData($tmp);
};
$up['items'] = function ($cmd, $token) {
  if ($token['type'] == 管理员) {
    $tmp = ['table' => 'items', 'where' => $cmd['where']];
    if (isset($cmd['cid'])) $tmp['cid'] = $cmd['cid'];
    if (isset($cmd['pid'])) $tmp['pid'] = $cmd['pid'];
    if (isset($cmd['uid'])) $tmp['uid'] = $cmd['uid'];
    if (isset($cmd['name'])) $tmp['name'] = $cmd['name'];
    if (isset($cmd['units'])) $tmp['units'] = json_encode($cmd['units'], JSON_UNESCAPED_UNICODE);
    // if (isset($cmd['sum'])) $tmp['sum'] = $cmd['sum'];
    if (isset($cmd['other'])) $tmp['other'] = json_encode($cmd['other'], JSON_UNESCAPED_UNICODE);
  } else return noPrem;
  $ret = UpData($tmp);
  if (is_string($ret['units'])) $ret['units'] = json_decode($ret['units'], true);
  if (is_string($ret['other'])) $ret['other'] = json_decode($ret['other'], true);
  return ['result' => $ret];
};
$up['itemIO'] = function () {
  return ['msg' => 'itemIO 不允许修改'];
};
$up['userType'] = function ($cmd, $token) {
  if ($token['type'] == 管理员) {
    $tmp = ['table' => strtolower('userType'), 'where' => $cmd['where']];
    if (isset($cmd['cid'])) $tmp['cid'] = $cmd['cid'];
    if (isset($cmd['pid'])) $tmp['pid'] = $cmd['pid'];
    if (isset($cmd['name'])) $tmp['name'] = $cmd['name'];
    if (isset($cmd['other'])) $tmp['other'] = $cmd['other'];
  } else return noPrem;
  $ret = UpData($tmp);
  return ['result' => $ret];
};
$up['users'] = function ($cmd, $token) {
  $gly = $token['type'] == 管理员;
  $tmp = [
    'table' => strtolower('users'),
    'where' => ($cmd['where'] && $gly) ? $cmd['where'] : ['id' => $token['id']],
    'ChangeTime' => time(),
  ];
  if (isset($cmd['state']) && $gly) $tmp['state'] = $cmd['state'];
  if (isset($cmd['type']) && $gly) $tmp['type'] = $cmd['type'];
  if (isset($cmd['password'])) $tmp['password'] = $cmd['password'];
  if (isset($cmd['name'])) $tmp['name'] = $cmd['name'];
  if (isset($cmd['tel'])) $tmp['tel'] = $cmd['tel'];
  if (isset($cmd['userType'])) $tmp['userType'] = (int) $cmd['userType'];
  if (isset($cmd['other'])) $tmp['other'] = json_encode($cmd['other'], JSON_UNESCAPED_UNICODE);

  $ret = UpData($tmp);
  if (isset($ret['other']) && is_string($ret['other'])) $ret['other'] = json_decode($ret['other'], true);
  return ['result' => $ret];
};
$up['process'] = function ($cmd, $token) {
  if ($token['type'] == 管理员) {
    $tmp = ['table' => 'process', 'where' => $cmd['where']];
    if ($cmd['name']) $tmp['name'] = $cmd['name'];
    if ($cmd['other']) $tmp['other'] = $cmd['other'];
    if (isset($cmd['state'])) $tmp['state'] = $cmd['state'];
  } else return noPrem;
  $ret = UpData($tmp);
  return ['result' => $ret];
};

$up['project'] = function ($cmd, $token) {
  if (!($token['type'] == 管理员 || $token['type'] == 信息员)) return noPrem;
  if (!(isArray($cmd['info']) &&
    isset($cmd['info']['id']))) return ['error' => 'val格式错误', 'data' => $cmd];
  $cmd = $cmd['info'];
  if (!$cmd['id']) {
    if (!($cmd['pid'] && $cmd['name'] && $cmd['userType'])) return ['error' => '数据格式错误.必须包含 id/(pid,name,userType items)'];
    $cmd['id'] = getProjectByName($cmd['name'], $cmd['pid'], $cmd['userType']);
  }

  $sql = ['table' => 'project', 'where' => ['id' => (int) $cmd['id']]];
  $t = GetData(['table' => 'project', 'id' => (int) $cmd['id']], '*', true);
  if ($t['error']) $ret = $t;
  elseif ($token['type'] == 管理员 || ($token['type'] == 信息员 && in_array($t['userType'], $token['uts']))) { // 有权限
    if (isset($cmd['userType']) && (int) $cmd['userType'] != $t['userType']) $sql['userType'] = (int) $cmd['userType'];
    if (isset($cmd['name']) && $cmd['name'] != $t['name']) $sql['name'] = $cmd['name'];
    // if (isset($cmd['process']) && $cmd['process'] != json_decode($t['process'], true)) $sql['process'] =  json_encode($cmd['process']);
    if (isset($cmd['process']) && $cmd['process'] != $t['process']) $sql['process'] =  $cmd['process'];
    if (isset($cmd['other']) && $cmd['other'] != $t['other']) $sql['other'] =  json_encode($cmd['other']);
    if (isset($cmd['state']) && (int) $cmd['state'] != $t['state']) $sql['state'] = (int) $cmd['state'];
    if (count(array_keys($sql)) > 2) $ret = UpData($sql); // 更新无关联数据
    if ($ret['error']) return $ret;
    $qqq = [];
    if ($cmd['pid']) {
      $stock = GetData(['table' => 'stock', 'depository' => 0, 'project' => (int) $cmd['id']]);
      $add = [];
      $ts = [];
      if ($stock['error']) $stock = [];
      foreach ($cmd['items'] as $i) {
        $process = is_numeric($i['process']) ? (int) $i['process'] : getProcessByName($i['process']);
        $item = 0;
        if ((int) $i['item']) $item = (int) $i['item'];
        elseif ($i['name']) {
          $t = GetData(['table' => 'items', 'uid' => $i['uid'], 'name' => $i['name'], 'model' => $i['model'] ? $i['model'] : '',], 'id,name');
          if ($t['error']) { //添加物料
            $t = AddData([
              'table' => 'items',
              'cid' => 0,
              'pid' => 1,
              'uid' => $i['uid'],
              'name' => $i['name'],
              'model' => $i['model'] ? $i['model'] : '',
              'units' => '[]',
              'sum' => 0,
              'state' => 1,
              'other' => '{"remarks":"批量添加"}'
            ]);
            $item = $t['id'];
          } else {
            $item = $t[0]['id'];
          }
        } else return ['error' => 'items必须包含 item/(name,uid,model) process sum ', 'data' => $cmd];
        $t = getItem($stock, ['id' => (int) $i['id']], 0);
        $tmp = [
          'table' => 'stock',
          'depository' => 0,
          'project' => (int) $cmd['id'],
          'item' => $item,
          'process' => $process,
          'sum' => (float) $i['sum'],
          'arrived' => 0,
          '`use`' => 0,
          'stock' => 0,
          'state' => 0
        ];
        $ts[] = $t;
        if ($t < 0) {
          // $add[] = AddData($tmp);
          $t = getItem($add, [
            'project' => $tmp['project'],
            'item' => $tmp['item'],
            'process' => $tmp['process'],
          ], 0);
          if ($t < 0) {
            // $qqq[] = $tmp;
            $add[] = $tmp;
          }
        } else {
          array_splice($stock, $t, 1);
          $t = $tmp;
          $t['where'] = ['id' => (int) $i['id']];
          $qqq[] = ['up1', UpData($t)];
        }
      }
      while (count($stock)) {
        $t = ['table' => 'stock', 'sum' => 0];
        if (count($add)) {
          $t = $add[0];
          array_splice($add, 0, 1);
        }
        $t['where'] = ['id' => $stock[0]['id']];
        array_splice($stock, 0, 1);
        $qqq[] = ['up2', UpData($t)];
      }
      foreach ($add as $v) {
        $qqq[] = ['add', AddData($v)];
      }
      // return $qqq;
      $ret = ['result' => getGlobal4(0, $token)];
    }
  } else $ret = noPrem;
  return $ret;
};
